package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.exception.LoginFailedException;
import com.jixi.common.utils.Md5Util;
import com.jixi.mapper.SchoolMapper;
import com.jixi.mapper.TeacherMapper;
import com.jixi.pojo.dto.TeacherLoginDto;
import com.jixi.pojo.entity.School;
import com.jixi.pojo.entity.Teacher;
import com.jixi.pojo.vo.TeacherVo;
import com.jixi.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService{
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    /**
     * 班主任信息查询
     * */
    @Override
    public TeacherVo getTeacherDetail() {
        Long teacherId = StpUtil.getLoginIdAsLong();
        Teacher teacher = teacherMapper.selectById(teacherId);
        TeacherVo teacherVo = new TeacherVo();
        BeanUtils.copyProperties(teacher,teacherVo);
        return teacherVo;
    }
    /**
     * 班主任登录
     *
     * @param teacherLoginDto
     * @return 登录结果
     * */
    @Override
    public void login(TeacherLoginDto teacherLoginDto) {
        //根据学校id查询学校,绑定学校查询
        LambdaQueryWrapper<School> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(School::getSchoolId,teacherLoginDto.getSchoolId())
                     .eq(School::getSchoolName,teacherLoginDto.getSchoolName());
        School school = schoolMapper.selectOne(queryWrapper1);
        if (school == null){
             throw new LoginFailedException("学校名称有误");
        }
        //构造查询
        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        //以username,学校id作为查询依据
        queryWrapper.eq(Teacher::getTeacherUsername, teacherLoginDto.getTeacherUsername());
        queryWrapper.eq(Teacher::getSchoolId,school.getSchoolId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        //判断账号密码
        String password = Md5Util.getMD5String(teacherLoginDto.getTeacherPassword());
        if (teacher == null || ! password.equals(teacher.getTeacherPassword())) {
            throw new LoginFailedException("账号或密码错误");
        }
        //查询禁用状态
        if (teacher.getStatus() == 0) {
            throw new LoginFailedException("账号已禁用，请联系学校管理员");
        }
        //使用sa-token登录
        StpUtil.login(teacher.getTeacherId());
    }
}
